<!-- pages/login.vue -->
<template>
    <div class="auth-page">
        <main class="auth-container">
            <form class="auth-form" @submit.prevent="handleLogin">
                <h2>手机号登录</h2>
                <div class="form-group">
                    <div class="input-wrapper">
                        <img src="/icon/register/icon1.png" class="input-icon">
                        <input v-model="form.username" type="tel" placeholder="请输入手机号" maxlength="11"
                            @blur="validateField('username')" />
                    </div>
                    <span v-if="errors.username" class="error">{{ errors.username }}</span>
                </div>

                <div class="form-group">
                    <div class="input-wrapper">
                        <img src="/icon/register/icon2.png" class="input-icon">
                        <input v-model="form.password" type="password" placeholder="请输入密码（6-20位字母+数字）"
                            @blur="validateField('password')" />
                    </div>
                    <span v-if="errors.password" class="error">{{ errors.password }}</span>
                </div>

                <button type="submit" class="submit-btn">登录</button>

                <div class="auth-footer">
                    <div class="links">
                        <NuxtLink :to="localePath('/ForgotPassword')">忘记密码？</NuxtLink>
                        <NuxtLink :to="localePath('/Register')">去注册</NuxtLink>
                    </div>
                </div>
            </form>
        </main>
    </div>
</template>

<script setup>
import { sm2 } from 'sm-crypto' // 添加sm-crypto导入
import Base64 from 'crypto-js/enc-base64';
import Hex from 'crypto-js/enc-hex';
const router = useRouter()
const route = useRoute()
const localePath = useLocalePath()
const { $fetchGov, $fetchAuth } = useNuxtApp()

const useStore = useUserStore(); //pinia

definePageMeta({
    layout: 'login-layout' // 使用 custom-layout.vue 作为布局
});

const { data: sm2Key } = await useAsyncData(
    'sm2Key',
    () => $fetchGov('/app/api/env/client-public-key', {
        method: 'GET',
        params: {
            _t: Date.now()
        }
    })
)

const form = reactive({
    username: '',
    password: ''
})

const errors = reactive({
    username: '',
    password: ''
})

// 验证规则集合
const validators = {
    username: () => {
        if (!form.username) return '手机号不能为空'
        if (!/^1[3-9]\d{9}$/.test(form.username)) return '手机号格式不正确'
        return ''
    },
    password: () => {
        if (!form.password) return '密码不能为空'
        if (form.password.length < 6 || form.password.length > 20)
            return '密码长度6-20位'
        if (!/^(?=.*[a-zA-Z])(?=.*\d).+$/.test(form.password))
            return '需包含字母和数字'
        return ''
    }
}

// 单个字段验证
const validateField = (field) => {
    errors[field] = validators[field]()
}

// 提交验证
const validateAll = () => {
    return Object.keys(validators).every(field => {
        errors[field] = validators[field]()
        return !errors[field]
    })
}

const handleLogin = async () => {
    if (!validateAll()) return

    try {
        // 加密密码
        const encryptedPassword = Base64.stringify(Hex.parse('04' + sm2.doEncrypt(form.password, sm2Key.value.data, 1)))
        // 登录成功处理
        const { data: responseData } = await $fetchGov('/api/auth/jwt/login', {
            method: 'POST',
            body: {
                ...form,
                password: encryptedPassword // 替换为加密后的密码
            },
        });

        if (responseData.status === 0) {
            useStore.setToken({
                accessToken: responseData.result.accessToken,
                refreshToken: responseData.result.refreshToken
            });

            // 添加延迟确保 token 存储完成
            await new Promise(resolve => setTimeout(resolve, 50))
            
            const { data: userData } = await $fetchAuth('/app/api/user', {
                method: 'GET'
            });
            if (userData.status === 0) {
                useStore.setUser(userData)
                const redirect = route.query.redirect
                ElMessage.success('登录成功')
                setTimeout(() => {
                    router.push(
                        redirect ? decodeURIComponent(redirect) : localePath('/')
                    )
                }, 50)
            }else{
                ElMessage.error(userData.message)
            }
        } else {
            ElMessage.error(responseData.message)
        }
    } catch (err) {
        console.error('登录失败:', err)
    }
}
</script>

<style lang="scss" scoped>
@use '@/assets/scss/login/index' as *;

.links {
    display: flex;
    justify-content: space-between;
    margin-top: 1rem;
}
</style>